package mcts;

import java.util.Iterator;

public class GoGameTreeSonsList implements Iterable<GoGameTree>{
	
	GoGameTree node;
	GoGameTreeSonsList next;
	
	public GoGameTreeSonsList(GoGameTree n) {
		node = n;
		next = null;
	}
	
	public GoGameTreeSonsList(GoGameTree n, GoGameTreeSonsList l) {
		node = n;
		next = l;
	}
	
	public GoGameTree getNode() {
		return node;
	}
	
	public int getLength() {
		if (next == null) return 1;
		return 1+next.getLength();
	}
	
	public GoGameTreeSonsList getNext() {
		return next;
	}
	
	public GoGameTreeSonsList updatePosition(GoGameTree n, int global_time) {
		// WARNING: n must belong to the list
		
		// n is the only element of the list
		if (next == null) return this;
		
		GoGameTreeSonsList res = this.delete(n);
		return res.insert(n,global_time);
	}
	
	public GoGameTreeSonsList insert(GoGameTree n, int global_time) {
		if (node.getEvaluation(global_time) < n.getEvaluation(global_time)) {
			return new GoGameTreeSonsList(n,this);
		} else {
			if (next == null) {
				next = new GoGameTreeSonsList(n);
				return this;
			} else {
				next = next.insert(n,global_time);
				return this;
			}
		}
	}
	
	public GoGameTreeSonsList delete(GoGameTree n) {
		
		// n is the node we are examining
		if (n == node) {
			return next;
		}
		
		// n is not in the list
		if (next == null) return this;
		
		// n is (maybe) in the rest of the list
		next = next.delete(n);
		return this;
		
	}
	
	public GoGameTree getFirst() {
		return node;
	}
	
	public GoGameTree getLast() {
		if (next == null) return node;
		
		return next.getLast();
	}

	public Iterator<GoGameTree> iterator() {
		return new GoGameTreeSonsListIterator(this);
	}
}
